package org.hbhk.aili.job.configuration;

import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;

public abstract class CommonJob implements SimpleJob {

	Logger log = LoggerFactory.getLogger(CommonJob.class);

	String startSql = "insert  into job_log(task_id,job_name,start_time) values (?,?,?)";

	String endSql = "update  job_log  set  end_time = ?,  err_msg=? ,status=?   where task_id = ? ";

	private JdbcTemplate jdbcTemplate;

	public abstract void doExecute(ShardingContext shardingContext);

	@Override
	public void execute(ShardingContext shardingContext) {
		String uuid = UUID.randomUUID().toString();
		try {
			jdbcTemplate = ElasticScheduler.applicationContext.getBean(JdbcTemplate.class);
			String jobName = shardingContext.getJobName();
			if (jdbcTemplate != null) {
				Object[] args = new Object[] { uuid, jobName, new Date() };
				jdbcTemplate.update(startSql, args);
			}
			doExecute(shardingContext);

			if (jdbcTemplate != null) {
				Object[] args = new Object[] { new Date(), "1", '1', uuid };
				jdbcTemplate.update(endSql, args);
			}

		} catch (Exception e) {
			if (jdbcTemplate != null) {
				String err = ExceptionUtils.getMessage(e);
				err = err.replaceAll("\r|\n", "");
				String status = "0";
				if (err.contains("请求超时")) {
					status = "1";
				}
				if (err.length() > 500) {
					err = err.substring(0, 499);
				}
				Object[] args = new Object[] { new Date(), err, status, uuid };
				jdbcTemplate.update(endSql, args);
			}
			throw new RuntimeException(e);
		}

	}

}
